const { getDocumentStore } = require('../store');
const { embeddingService } = require('./embedding.service');
const { logger } = require('../utils/logger');

async function createDocument(payload) {
  const store = getDocumentStore();
  const doc = await store.create({
    ...payload,
    metadata: payload.metadata || {},
    vector: payload.vector || null
  });

  if (!doc.vector && payload.autoEmbed === true && payload.content) {
    try {
      const vector = await embeddingService.embedText(payload.content);
      return store.updateVector(doc.id, vector);
    } catch (error) {
      logger.warn({ err: error }, 'Failed to embed document automatically');
    }
  }

  return doc;
}

async function updateDocument(id, payload) {
  const store = getDocumentStore();
  const existing = await store.findById(id);
  if (!existing) return null;

  const next = await store.update(id, {
    ...payload,
    metadata: { ...existing.metadata, ...payload.metadata }
  });

  if (payload.autoEmbed === true && payload.content) {
    try {
      const vector = await embeddingService.embedText(payload.content);
      return store.updateVector(id, vector);
    } catch (error) {
      logger.warn({ err: error }, 'Failed to embed document automatically on update');
    }
  }

  return next;
}

async function updateVector(id, vector) {
  const store = getDocumentStore();
  return store.updateVector(id, vector);
}

async function deleteDocument(id) {
  const store = getDocumentStore();
  return store.remove(id);
}

async function getDocument(id) {
  const store = getDocumentStore();
  return store.findById(id);
}

async function listDocuments(limit = 50, offset = 0) {
  const store = getDocumentStore();
  return store.list({ limit: Number(limit) || 50, offset: Number(offset) || 0 });
}

async function searchDocuments({ query, tags = [], limit = 20 }) {
  const store = getDocumentStore();
  return store.search({ query, tags, limit });
}

async function searchByVector(vector, limit = 20) {
  const store = getDocumentStore();
  if (typeof store.searchByVector === 'function') {
    const results = await store.searchByVector(vector, limit);
    if (results?.length) return results;
  }
  return embeddingService.similaritySearch(vector, limit);
}

module.exports = {
  documentService: {
    createDocument,
    updateDocument,
    updateVector,
    deleteDocument,
    getDocument,
    listDocuments,
    searchDocuments,
    searchByVector
  }
};
